﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Project_2._2.Models;
using Project_2._2.ViewModels;
using Project_2._2.Extra;
using System.Web.Security;
using PagedList;
using PagedList.Mvc;

namespace Project_2._2.Controllers
{
    public class AdminPersonController : Controller
    {
        private QuanLyThueXeEntities db = new QuanLyThueXeEntities();
        private Common cm = new Common();
        #region Default
        // GET: /AdminPerson/
        public ActionResult Default( int? page, string rd,string Record, string key , string SBy, string SType)
        {
            
            if (!Request.IsAuthenticated)
            {
                return RedirectToAction("Login", "Admin");
            }
            else
            {
                if (cm.CheckUserType(User.Identity.Name))
                {
                    if (rd != null)
                    {
                        int soDong = int.Parse(rd);
                        string k = key;
                        string b = SBy;
                        string t = SType;
                        IPagedList<Person> person = null;
                        if (!string.IsNullOrEmpty(k) && b != "0")
                        {
                            ViewBag.Key = k;
                            ViewBag.SBy = b;
                            ViewBag.SType = t;

                            switch (b)
                            {
                                case "ID":
                                    int s = 0;
                                    try
                                    {
                                        s = int.Parse(key);
                                        person = (from p in db.People where p.PersonId == s select p).ToList().ToPagedList(page ?? 1, soDong);
                                    }
                                    catch (Exception)
                                    {
                                        return View(person);
                                    }
                                    break;
                                case "UserName":
                                    if (t == "1")
                                        person = (from p in db.People where p.TenDangNhap.Contains(key) select p).ToList().ToPagedList(page ?? 1, soDong);
                                    else
                                    { person = (from p in db.People where p.TenDangNhap.Equals(key) select p).ToList().ToPagedList(page ?? 1, soDong); }
                                    break;
                                case "Name":
                                    if (t == "1")
                                        person = (from p in db.People where p.HoTen.Contains(key) select p).ToList().ToPagedList(page ?? 1, soDong);
                                    else
                                    {
                                        person = (from p in db.People where p.HoTen.Equals(key) select p).ToList().ToPagedList(page ?? 1, soDong);
                                    }
                                    break;
                                case "Phone":
                                    if (t == "1")
                                        person = (from p in db.People where p.DienThoai.Contains(key) select p).ToList().ToPagedList(page ?? 1, soDong);
                                    else
                                    { person = (from p in db.People where p.DienThoai.Equals(key) select p).ToList().ToPagedList(page ?? 1, soDong); }
                                    break;
                                case "Email":
                                    if (t == "1")
                                        person = (from p in db.People where p.Email.Contains(key) select p).ToList().ToPagedList(page ?? 1, soDong);
                                    else
                                    { person = (from p in db.People where p.Email.Equals(key) select p).ToList().ToPagedList(page ?? 1, soDong); }
                                    break;
                            }
                        }
                        else
                        {
                            person = (from p in db.People select p).ToList().ToPagedList(page ?? 1, soDong);
                        }
                        
                       ViewBag.record = rd;
                       return View(person);
                    }
                    else
                    {
                        var person = (from p in db.People select p).ToList().ToPagedList(page ?? 1, 1);
                        return View(person);
                    }
                }
                else
                    return RedirectToAction("Login", "Admin");
            }          
            
        }
        //POST
        [HttpPost]
        public ActionResult Default( FormCollection col, int? page)
        {
            int  soDong = int.Parse(col["soDong"]);
            string SearchBy = col["SearchBy"] ;
            string SearchType = col["SearchType"]; 
            string key = col["KeyWorld"] ;
            IPagedList<Person> person = null;

            //
            ViewBag.Key = key;
            ViewBag.SBy = SearchBy;
            ViewBag.SType = SearchType;
            ViewBag.record = soDong.ToString();

            if (string.IsNullOrEmpty(key))
            {
                person = (from p in db.People select p).ToList().ToPagedList(page ?? 1, soDong);                
                return View(person);
            }
            else
            {        
                
                switch(SearchBy)
                {
                    case "ID":
                                int s = 0;
                                try
                                {
                                    s = int.Parse(key);
                                    person = (from p in db.People where p.PersonId == s select p).ToList().ToPagedList(page ?? 1, soDong);
                                }
                                catch (Exception)
                                {
                                    return View(person);
                                }                     
                                break;
                    case "UserName":
                                if (SearchType == "1")
                                    person = (from p in db.People where p.TenDangNhap.Contains(key) select p).ToList().ToPagedList(page ?? 1, soDong);
                                else
                                { person = (from p in db.People where p.TenDangNhap.Equals(key) select p).ToList().ToPagedList(page ?? 1, soDong); }
                                break;
                    case "Name":
                                if (SearchType == "1")
                                    person = (from p in db.People where p.HoTen.Contains(key) select p).ToList().ToPagedList(page ?? 1, soDong);
                                else
                                {
                                    person = (from p in db.People where p.HoTen.Equals(key) select p).ToList().ToPagedList(page ?? 1, soDong);
                                }                                
                                break;
                    case "Phone":
                                if (SearchType == "1")
                                    person = (from p in db.People where p.DienThoai.Contains(key) select p).ToList().ToPagedList(page ?? 1, soDong);
                                else
                                { person = (from p in db.People where p.DienThoai.Equals(key) select p).ToList().ToPagedList(page ?? 1, soDong); }
                                break;
                    case "Email":
                                if (SearchType == "1")
                                    person = (from p in db.People where p.Email.Contains(key) select p).ToList().ToPagedList(page ?? 1, soDong);
                                else
                                { person = (from p in db.People where p.Email.Equals(key) select p).ToList().ToPagedList(page ?? 1, soDong); }
                                 break;

                }
                return View( person);
            }
        }
        #endregion

        #region Create
        // GET: /AdminPerson/
        public ActionResult Create()
        {
            return View();
        }
        //POST
        [HttpPost]
        public ActionResult Create(AdminPerson_Create_ViewModels person)
        {
            
            if (ModelState.IsValid)
            {
                if (cm.CheckUserName(person.UserName) == true)
                    ModelState.AddModelError("UserName", "Tên Đăng Nhập này đã được đăng ký.");
                else if ((DateTime.Now.Year - person.DOB.Year) < 18)
                    ModelState.AddModelError("DOB", "Năm sinh không đủ 18 tuổi.");
                else
                {
                    // tao 1 person moi voi thong tin tu personViewModels
                    Person ps = new Person();
                    ps.TenDangNhap = person.UserName;
                    // ma hoa pass
                    string pass = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(person.Pass, "MD5");
                    ps.MatKhau = pass;
                    //
                    ps.NgaySinh = person.DOB;
                    ps.HoTen = person.Name;
                    ps.GioiTinh = person.GioiTinh;
                    ps.Email = person.Email;
                    ps.DienThoai = person.DienThoai;
                    ps.DiaChi = person.DiaChi;
                    ps.isDelete = person.isDelete;
                    ps.RoleId = person.RoleId;
                    // Add vao Db
                    db.People.Add(ps);
                    db.SaveChanges();
                    //return RedirectToAction("Default","Default");
                    
                    ModelState.Clear();
                    person = new AdminPerson_Create_ViewModels();
                    ModelState.AddModelError("", "Tạo tài khoản thành công.");
                }
            }
            return View(person);
        }
        #endregion

        #region Update
        // GET: /AdminPerson/
        
        public ActionResult Update(int id)
        {
            if (!Request.IsAuthenticated)
            {
                return RedirectToAction("Default", "Default");
            }
            else
            {
               var person = (from p in db.People where p.PersonId == id select p).First();
                return View(person);
            }
            
        }
        [HttpPost]
        public ActionResult Update(int id, FormCollection col)
        {
            var person = (from p in db.People where p.PersonId == id select p).First();
            person.RoleId = int.Parse(col["RoleId"]);
            person.HoTen = col["HoTen"];
            person.NgaySinh = DateTime.Parse( col["NgaySinh"]);
            person.GioiTinh = col["GioiTinh"];
            person.DienThoai = col["DienThoai"];
            person.Email = col["Email"];
            person.DiaChi = col["DiaChi"];
            //person.isDelete = col["isDelete"];

            UpdateModel(person);
            db.SaveChanges();
            ModelState.AddModelError("", "Cập nhật thành công.");
            return RedirectToAction("Default");
        }
        #endregion

        #region Delete
        // GET: /AdminPerson/
        public ActionResult Delete(int id)
        {
            if (!Request.IsAuthenticated)
            {
                return RedirectToAction("Default", "Default");
            }
            else
            {
                var person = (from p in db.People where p.PersonId == id select p).FirstOrDefault();
                db.People.Remove(person);
                db.SaveChanges();
                return RedirectToAction("Default","AdminPerson");
            }
            
        }
        #endregion

    }
}
